package com.kfm.mvn.listener;

import com.kfm.mvn.util.Constant;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
import java.util.Map;

@WebListener
public class OnlineUserListener implements HttpSessionAttributeListener {



    @Override
    public void attributeAdded(HttpSessionBindingEvent event) {
        String name = event.getName();
        // 登录操作
        if (Constant.LOGIN_USER.equals(name)){
            // 获取 map
            HttpSession session = event.getSession();
            Map<String, HttpSession> map = (Map<String, HttpSession>) session.getServletContext().getAttribute(Constant.ONLINE_USERS_KEY);
            String id = session.getId();
            map.put(id, session);
            System.out.println("用户 " + id + " 登录了");
        }
    }

    @Override
    public void attributeRemoved(HttpSessionBindingEvent event) {
        String name = event.getName();
        // 退出操作
        if (Constant.LOGIN_USER.equals(name)){
            HttpSession session = event.getSession();
            Map<String, HttpSession> map = (Map<String, HttpSession>) session.getServletContext().getAttribute(Constant.ONLINE_USERS_KEY);
            String id = session.getId();
            map.remove(id);
            System.out.println("用户 " + id + " 退出了");
        }
    }
}
